﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Security;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Timers;
using System.Windows.Forms;

using Microsoft.Win32;

using Microsoft.SharePoint.Administration;
using System.Configuration;
using System.IO;
using SharepointSolutionInstaller.Utils.RequiredChecks;
using SharepointSolutionInstaller.Utils;
using SharepointSolutionInstaller.Resources;
using SharepointSolutionInstaller.Utils.Configuration;


namespace SharepointSolutionInstaller.Views
{
    public partial class CheckPrerequisiteView : InstallerControl
    {

        private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();

        private bool requireMOSS;
        private bool requireSearchSKU;
        private SystemCheckList checks;
        private int nextCheckIndex;
        private int errors;

        #region Ctor

        public CheckPrerequisiteView()
        {
            InitializeComponent();
            this.Load += new EventHandler(SystemCheckControl_Load);
            this.Title = Resources.CommonUIStrings.controlTitleSystemCheck;
            this.SubTitle = InstallConfiguration.FormatString(Resources.CommonUIStrings.controlSubTitleSystemCheck);
        }

        #endregion

        #region Public Properties

        public bool RequireMOSS
        {
            get { return requireMOSS; }
            set { requireMOSS = value; }
        }

        public bool RequireSearchSKU
        {
            get { return requireSearchSKU; }
            set { requireSearchSKU = value; }
        }

        #endregion

        #region Event Handlers

        private void SystemCheckControl_Load(object sender, EventArgs e)
        {
        }

        private void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
        {
            timer.Stop();

            if (nextCheckIndex < checks.Count)
            {
                if (ExecuteCheck(nextCheckIndex))
                {
                    nextCheckIndex++;
                    timer.Start();
                    return;
                }
            }

            FinalizeChecks();
        }

        #endregion

        #region Protected Methods

        protected internal override void Open(InstallOptions options)
        {
            if (checks == null)
            {
                Form.btnNext.Enabled = false;
                Form.btnPrevious.Enabled = false;

                checks = new SystemCheckList();
                InitializeChecks();

                timer.Interval = 100;
                timer.Tick += new EventHandler(TimerEventProcessor);
                timer.Start();
            }
        }

        protected internal override void Close(InstallOptions options)
        {
        }

        #endregion

        #region Private Methods

        private void InitializeChecks()
        {
            this.tableLayoutPanel.SuspendLayout();

            //
            // WSS Installed Check
            //
            WSSInstalledCheck wssCheck = new WSSInstalledCheck();
            wssCheck.QuestionText = CommonUIStrings.wssCheckQuestionText;
            wssCheck.OkText = CommonUIStrings.wssCheckOkText;
            wssCheck.ErrorText = CommonUIStrings.wssCheckErrorText;
            AddCheck(wssCheck);

            //
            // MOSS Installed Check
            //
            if (requireMOSS)
            {
                MOSSInstalledCheck mossCheck = new MOSSInstalledCheck();
                mossCheck.QuestionText = CommonUIStrings.mossCheckQuestionText;
                mossCheck.OkText = CommonUIStrings.mossCheckOkText;
                mossCheck.ErrorText = CommonUIStrings.mossCheckErrorText;
                AddCheck(mossCheck);
            }

            //
            // Admin Rights Check
            //
            AdminRightsCheck adminRightsCheck = new AdminRightsCheck();
            adminRightsCheck.QuestionText = CommonUIStrings.adminRightsCheckQuestionText;
            adminRightsCheck.OkText = CommonUIStrings.adminRightsCheckOkText;
            adminRightsCheck.ErrorText = CommonUIStrings.adminRightsCheckErrorText;
            AddCheck(adminRightsCheck);

            //
            // Admin Service Check
            //
            AdminServiceCheck adminServiceCheck = new AdminServiceCheck();
            adminServiceCheck.QuestionText = CommonUIStrings.adminServiceCheckQuestionText;
            adminServiceCheck.OkText = CommonUIStrings.adminServiceCheckOkText;
            adminServiceCheck.ErrorText = CommonUIStrings.adminServiceCheckErrorText;
            AddCheck(adminServiceCheck);

            //
            // Timer Service Check
            //
            TimerServiceCheck timerServiceCheck = new TimerServiceCheck();
            timerServiceCheck.QuestionText = CommonUIStrings.timerServiceCheckQuestionText;
            timerServiceCheck.OkText = CommonUIStrings.timerServiceCheckOkText;
            timerServiceCheck.ErrorText = CommonUIStrings.timerServiceCheckErrorText;
            AddCheck(timerServiceCheck);

            //
            // Solution File Check
            //
            SolutionFileCheck solutionFileCheck = new SolutionFileCheck(InstallConfiguration.SolutionFile);
            solutionFileCheck.QuestionText = CommonUIStrings.solutionFileCheckQuestionText;
            solutionFileCheck.OkText = InstallConfiguration.FormatString(CommonUIStrings.solutionFileCheckOkText, InstallConfiguration.SolutionTitle);
            AddCheck(solutionFileCheck);

            //
            // Solution Check
            //
            SolutionCheck solutionCheck = new SolutionCheck(InstallConfiguration.SolutionId, InstallConfiguration.SolutionTitle);
            solutionCheck.QuestionText = String.Format(CommonUIStrings.solutionCheckQuestionText, InstallConfiguration.SolutionTitle);
            solutionCheck.OkText = InstallConfiguration.FormatString(CommonUIStrings.solutionFileCheckOkText);
            solutionCheck.ErrorText = String.Format(CommonUIStrings.solutionCheckErrorText, InstallConfiguration.SolutionTitle);
            AddCheck(solutionCheck);

            //
            // Office Solution File Check
            //
            SolutionFileCheck officeSolutionFileCheck = new SolutionFileCheck(InstallConfiguration.OfficeSolutionFile);
            officeSolutionFileCheck.QuestionText = CommonUIStrings.officeSolutionFileCheckQuestionText;
            officeSolutionFileCheck.OkText = String.Format(CommonUIStrings.solutionFileCheckOkText, InstallConfiguration.OfficeSolutionTitle);
            AddCheck(officeSolutionFileCheck);

            //
            // Office Solution Check
            //
            SolutionCheck officeSolutionCheck = new SolutionCheck(InstallConfiguration.OfficeSolutionId, InstallConfiguration.OfficeSolutionTitle);
            officeSolutionCheck.QuestionText = String.Format(CommonUIStrings.solutionCheckQuestionText, InstallConfiguration.OfficeSolutionTitle);
            officeSolutionCheck.OkText = String.Format(CommonUIStrings.solutionFileCheckOkText, InstallConfiguration.OfficeSolutionFile);
            solutionCheck.ErrorText = String.Format(CommonUIStrings.solutionCheckErrorText, InstallConfiguration.OfficeSolutionTitle);
            AddCheck(officeSolutionCheck);


            //
            // Add empty row that will eat up the rest of the 
            // row space in the layout table.
            //
            this.tableLayoutPanel.RowCount++;
            this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));

            this.tableLayoutPanel.ResumeLayout(false);
            this.tableLayoutPanel.PerformLayout();
        }

        private bool ExecuteCheck(int index)
        {
            SystemCheck check = checks[index];
            string imageLabelName = "imageLabel" + index;
            string textLabelName = "textLabel" + index;
            Label imageLabel = (Label)tableLayoutPanel.Controls[imageLabelName];
            Label textLabel = (Label)tableLayoutPanel.Controls[textLabelName];

            try
            {
                SystemCheckResult result = check.Execute();
                if (result == SystemCheckResult.Success)
                {
                    if (index == 7)
                        isOfficeSolutionFileExist = true;

                    imageLabel.Image = global::SharepointSolutionInstaller.Properties.ResourceImg.CheckOk;
                    textLabel.Text = check.OkText;

                }
                else if (result == SystemCheckResult.Error)
                {
                    errors++;
                    imageLabel.Image = global::SharepointSolutionInstaller.Properties.ResourceImg.CheckFail;
                    textLabel.Text = check.ErrorText;
                }
                else if (result == SystemCheckResult.OfficeError)
                {
                    imageLabel.Image = global::SharepointSolutionInstaller.Properties.ResourceImg.CheckFail;
                    textLabel.Text = string.Format(CommonUIStrings.installExceptionFileNotFound, InstallConfiguration.OfficeSolutionFile);
                }
                //
                // Show play icon on next check that will run.
                //
                int nextIndex = index + 1;
                string nextImageLabelName = "imageLabel" + nextIndex;
                Label nextImageLabel = (Label)tableLayoutPanel.Controls[nextImageLabelName];
                if (nextImageLabel != null)
                {
                    nextImageLabel.Image = global::SharepointSolutionInstaller.Properties.ResourceImg.CheckPlay;
                }

                return true;
            }

            catch (Exception ex)
            {
                errors++;
                imageLabel.Image = global::SharepointSolutionInstaller.Properties.ResourceImg.CheckFail;
                textLabel.Text = ex.Message;
            }

            return false;
        }

        private void FinalizeChecks()
        {
            if (errors == 0)
            {
                ConfigureControls();
                Form.btnNext.Enabled = true;
                messageLabel.Text = CommonUIStrings.messageLabelTextSuccess;
            }
            else
            {
                messageLabel.Text = InstallConfiguration.FormatString(CommonUIStrings.messageLabelTextError);
            }

            Form.btnPrevious.Enabled = true;
        }

        private void AddCheck(SystemCheck check)
        {
            int row = tableLayoutPanel.RowCount;

            Label imageLabel = new Label();
            imageLabel.Dock = System.Windows.Forms.DockStyle.Fill;
            imageLabel.Image = global::SharepointSolutionInstaller.Properties.ResourceImg.CheckWait;
            imageLabel.Location = new System.Drawing.Point(3, 0);
            imageLabel.Name = "imageLabel" + row;
            imageLabel.Size = new System.Drawing.Size(24, 20);

            Label textLabel = new Label();
            textLabel.AutoSize = true;
            textLabel.Dock = System.Windows.Forms.DockStyle.Fill;
            textLabel.Location = new System.Drawing.Point(33, 0);
            textLabel.Name = "textLabel" + row;
            textLabel.Size = new System.Drawing.Size(390, 20);
            textLabel.Text = check.QuestionText;
            textLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;

            this.tableLayoutPanel.Controls.Add(imageLabel, 0, row);
            this.tableLayoutPanel.Controls.Add(textLabel, 1, row);
            this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F));
            this.tableLayoutPanel.RowCount++;

            checks.Add(check);
        }

        private void ConfigureControls()
        {
            SolutionCheck check = (SolutionCheck)checks["SolutionCheck"];
            SPSolution solution = check.Solution;
            SolutionCheck officeCheck = (SolutionCheck)checks[7];
            SPSolution officeSolution = officeCheck.Solution;
            if(officeSolution!=null){
            isOfficeSolutionInstalled=true;
            }
            else
                isOfficeSolutionInstalled=false;

            if (solution == null)
            {
                AddInstallControls();
            }
            else
            {
                Version installedVersion = InstallConfiguration.InstalledVersion;
                Version newVersion = InstallConfiguration.SolutionVersion;

                if (newVersion != installedVersion)
                {
                    Form.contentControls.Add(new UpgradeView());
                }
                else
                {
                    Form.contentControls.Add(new RepairView());
                }
            }
        }

        private void AddInstallControls()
        {
            //
            // Add EULA control if an EULA file was specified.
            //
            string filename = InstallConfiguration.EULA;
            if (!String.IsNullOrEmpty(filename))
            {
                Form.contentControls.Add(new EULAView());
            }
            Form.contentControls.Add(new DeploymentTargetsView());
        }

        #endregion

    }
}
